import $ from 'jquery';
import { QUERY_WHOIS_URL } from '@/js/api';
import Emitter from './eventBus';
import 'layer';
import DomainParser from '@/js/domainparser';
const whoisBox = {
  template: `
    <div class="whois-box">
      <div class="whois-title">
        <h1>域名信息（WHOIS）查询</h1>
        <div class="lead">查询域名所有者、到期日、所属注册商等详细 WHOIS 信息</div>
      </div>
      <div class="whois-search-box">
        <div class="input-group">
            <input id="js-whois-input" type="text" name="domain" placeholder="请输入域名，如yunfv.cn"
              v-model="domain"
              @keyup.enter="check(domain)"
              v-focus
            >
            <div class="input-group-append">
              <button class="button whois-button" id="js-whois-button" type="button"
                @click="check(domain)"
              ><i class="fa fa-search"></i></button>
            </div>
        </div>
      </div>
      <div class="whois-tips">
        <dl>
          <dt><i class="fa fa-lightbulb-o"></i> Whois 是什么？</dt>
          <dd>您可以用Whois来查看域名的当前信息状态，包括域名是否已被注册、注册日期、过期日期、域名状态、DNS解析服务器等。</dd>
        </dl>
      </div>
    </div>
  `,
  data: () => {
    return {
      domain: '',

    }
  },
  mounted: function(){
    if( typeof(initDomain) != "undefined" ){
      this.domain = initDomain;
      this.getWhois(this.domain)  
    }
  },
  methods: {
    check: function (domain) {
      let input = $('#js-whois-input').val();
      let parser = new DomainParser($.trim(input));
      parser.parse()
      if (parser.hasError()) {
        layer.alert(parser.getMessage())
        this.domain = "";
        return false;
      }
      this.domain = encodeURI(parser.getModifyName());
      this.getWhois(domain)
    },
    getWhois: function (domain) {
      Emitter.$emit('gettingData', true)
      $.getJSON(QUERY_WHOIS_URL, { "domain": this.domain }).then((data) => {
        Emitter.$emit('gettingData', false)
        switch (data.code) {
          case "1000":
            Emitter.$emit('getWhois', data.module)
            Emitter.$emit('isShrink', data.success)
            break;
          case "1001":
            layer.alert('未查询到注册信息，该域名可能尚未注册')
            break;
          case "4004":
            layer.alert('暂不支持该域名后缀查询')
            break;
          case "504":
            layer.alert('查询超时，请重试')
            break;
          default:
            layer.alert('未知错误，请重试')
        }
      }).fail(() => {
        Emitter.$emit('gettingData', false)
        layer.alert('查询失败，请重试')  
      })
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  }
}
module.exports = whoisBox;